from csv import *
import cgi, os
import wsgiref.handlers

from google.appengine.api import users
from google.appengine.ext import webapp 
from google.appengine.ext.webapp import template

from pyth import json
from pyth import populate
from pyth.inventionmodels import *
from pyth.purge import *

class JSONSearchAll(webapp.RequestHandler):
    def get(self):
        jsonArray = [];
        req = cgi.escape(self.request.get('search'));

        count = CodeSample.all().search(req).count()
        codeCount = {'count' : str(count)}
        samples = codeSamplesToJSON(CodeSample.all().search(req).fetch(limit=10))
        jsonArray.append(codeCount)
        jsonArray.append(samples)
        
        count = Workshop.all().search(req).count()
        workshopCount = {'count' : str(count)}
        workshops = workshopsToJSON(Workshop.all().search(req).fetch(limit=10))
        jsonArray.append(workshopCount)
        jsonArray.append(workshops)

        count = Theme.all().search(req).count()
        themesCount = {'count' : str(count)}
        themes = themesToJSON(Theme.all().search(req).fetch(limit=10))
        jsonArray.append(themesCount)
        jsonArray.append(themes)

        count = Material.all().search(req).count()
        materialCount = {'count' : str(count)}
        material = materialsToJSON(Material.all().search(req).fetch(limit=10))
        jsonArray.append(materialCount)
        jsonArray.append(material)

        self.response.out.write(json.write(jsonArray))

class JSONCount(webapp.RequestHandler):
    def modelType(self): abstract
    def get(self):
        req = cgi.escape(self.request.get('search'));
        count = self.modelType().all().search(req).count()
        item = {'count' : str(count)}
        self.response.out.write(json.write(item))

class JSONSearch(webapp.RequestHandler):
    def modelType(self): abstract
    def toJSON(self, entries): abstract
    def get(self):
        req = cgi.escape(self.request.get('search'));
        off = cgi.escape(self.request.get('offset'));
        if off:
            off = int(off)
        else:
            off = 0
        samples = self.modelType().all().search(req).fetch(limit=10, offset=off)
        self.response.out.write(json.write(self.toJSON(samples)))

## !!!!!!!!!!! BROKEN !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
## loading a page directly from a url will not work until this is fixed        
class JSONEntry(webapp.RequestHandler):
    def modelType(self): abstract
    def toJSON(self, entries): abstract
    def get(self):
#        req = cgi.escape(self.request.get('codeId'))
#        code = self.modelType().gql("WHERE id1 = :1", int(req))
#        self.response.out.write(json.write(self.toJSON(code)))
        req = cgi.escape(self.request.get('workshopId'))
        workshop = self.modelType().gql("WHERE recordId = :1", req)
        self.response.out.write(json.write(self.toJSON(workshop)))

#--------------------------------------------------------------
#                     Materials
#--------------------------------------------------------------
class JSONMaterialsCount(JSONCount):
    def modelType(self): 
        return Material
class JSONMaterials(JSONSearch):
    def modelType(self): 
        return Material
    def toJSON(self, entries):
        return materialsToJSON(entries)
class JSONMaterialEntry(JSONEntry):
    def modelType(self): 
        return Material
    def toJSON(self, entries):
        return materialsToJSON(entries)

#--------------------------------------------------------------
#                     Themes
#--------------------------------------------------------------
class JSONThemesCount(JSONCount):
    def modelType(self): 
        return Theme
class JSONThemes(JSONSearch):
    def modelType(self): 
        return Theme
    def toJSON(self, entries):
        return themesToJSON(entries)
class JSONThemeEntry(JSONEntry):
    def modelType(self): 
        return Theme
    def toJSON(self, entries):
        return themesToJSON(entries)

#--------------------------------------------------------------
#                     CodeSamples
#--------------------------------------------------------------
class JSONCodeSamplesCount(JSONCount):
    def modelType(self): 
        return CodeSample
class JSONCodeSamples(JSONSearch):
    def modelType(self): 
        return CodeSample
    def toJSON(self, entries):
        return codeSamplesToJSON(entries)
class JSONCodeEntry(JSONEntry):
    def modelType(self): 
        return CodeSample
    def toJSON(self, entries):
        return codeSamplesToJSON(entries)

#--------------------------------------------------------------
#                     Workshops
#--------------------------------------------------------------

class JSONWorkshopsCount(JSONCount):
    def modelType(self): 
        return Workshop
class JSONWorkshops(JSONSearch):
    def modelType(self): 
        return Workshop
    def toJSON(self, entries):
        return workshopsToJSON(entries)
class JSONWorkshopEntry(JSONEntry):
    def modelType(self): 
        return Workshop
    def toJSON(self, entries):
        return workshopsToJSON(entries)

class JSONWorkshopsMaterials(webapp.RequestHandler):
    def get(self):
        req = cgi.escape(self.request.get('workshopId'));
        workshop = Workshop.gql("WHERE recordId = :1", req)
        if workshop.count() > 0:
            self.response.out.write(json.write(materialsToJSON(workshop[0].materials())))

class JSONWorkshopsCodeSamples(webapp.RequestHandler):
    def get(self):
        req = cgi.escape(self.request.get('workshopId'));
        workshop = Workshop.gql("WHERE recordId = :1", req)
        if workshop.count() > 0:
            self.response.out.write(json.write(codeSamplesToJSON(workshop[0].codesamples())))

class JSONWorkshopsThemes(webapp.RequestHandler):
    def get(self):
        req = cgi.escape(self.request.get('workshopId'));
        workshop = Workshop.gql("WHERE recordId = :1", req)
        if workshop.count() > 0:
            self.response.out.write(json.write(relationalThemesToJSON(workshop[0].themes())))

class JSONWorkshopsFromMaterial(webapp.RequestHandler):
    def get(self):
        req = cgi.escape(self.request.get('material'));
#        response = []
#        workshops = Workshop.gql('WHERE craft = :1', req)
#        response.extend(workshopsToJSON(workshops))
#        workshops = Workshop.gql('WHERE software = :1', req)
#        response.extend(workshopsToJSON(workshops))
#        workshops = Workshop.gql('WHERE hardware = :1', req)
#        response.extend(workshopsToJSON(workshops))
#        self.response.out.write(json.write(response))
        mats = Material.gql("WHERE name = :1", req)
        if mats.count() > 0:
            self.response.out.write(json.write(workshopsToJSON(mats[0].workshops())))

class JSONWorkshopsFromCode(webapp.RequestHandler):
    def get(self):
        req = cgi.escape(self.request.get('codeId'));
#        workshops = Workshop.gql("WHERE codeId = '" + "cd%03d"%(int(req)) + "'")
#        self.response.out.write(json.write(workshopsToJSON(workshops)))        
        codes = CodeSample.gql("WHERE id1 = :1", int(req))
        if codes.count() > 0:
            self.response.out.write(json.write(workshopsToJSON(codes[0].workshops())))

class JSONWorkshopsFromTheme(webapp.RequestHandler):
    def get(self):
        req = cgi.escape(self.request.get('workshopIds'));
        req = req.split(", ")
        response = []
        for r in req:
            response.extend(workshopsToJSON(Workshop.gql("WHERE recordId = :1", r)))
        self.response.out.write(json.write(response))
      

def main():
  application = webapp.WSGIApplication(
                                       [ 
                                       ('/python/searchall', JSONSearchAll),
                                       ('/python/workshops', JSONWorkshops),
                                       ('/python/workshops/count', JSONWorkshopsCount),
                                       ('/python/workshops/fromcode', JSONWorkshopsFromCode),
                                       ('/python/workshops/fromtheme', JSONWorkshopsFromTheme),
                                       ('/python/workshops/frommaterial', JSONWorkshopsFromMaterial),
                                       ('/python/workshop/codesamples', JSONWorkshopsCodeSamples),
                                       ('/python/workshop/materials', JSONWorkshopsMaterials),
                                       ('/python/workshop/themes', JSONWorkshopsThemes),
                                       ('/python/workshop', JSONWorkshopEntry),
                                       ('/python/codesamples', JSONCodeSamples),
                                       ('/python/codesamples/count', JSONCodeSamplesCount),
                                       ('/python/codesample', JSONCodeEntry),
                                       ('/python/themes', JSONThemes),
                                       ('/python/themes/count', JSONThemesCount),
                                       ('/python/theme', JSONThemeEntry),
                                       ('/python/materials', JSONMaterials),
                                       ('/python/materials/count', JSONMaterialsCount),
                                       ('/python/material', JSONMaterialEntry),
                                       ('/python/purge', Purge),
                                       ('/python/clear', populate.ClearAll),
                                       ('/python/load', populate.LoadAll),
                                       ('/python/relational/clear', populate.ClearRelational),
                                       ('/python/relational/load', populate.LoadRelational),
                                       ('/python/workshops/clear', populate.ClearWorkshop),
                                       ('/python/workshops/load', populate.LoadWorkshop),
                                       ('/python/materials/clear', populate.ClearMaterial),
                                       ('/python/materials/load', populate.LoadMaterial),
                                       ('/python/codesamples/clear', populate.ClearCode),
                                       ('/python/codesamples/load', populate.LoadCode),
                                       ('/python/themes/clear', populate.ClearTheme),
                                       ('/python/themes/load', populate.LoadTheme)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == "__main__":

  main()
